﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using AjaxControlToolkit;

public partial class LoanProducts : System.Web.UI.Page
{
    private readonly string mCurrentModule = Credits.Module.ID;
    private readonly string mPageName = "Administrarea Produselor de creditare";
    private string appPath = string.Empty;
    bool allowViewLoanProduct = false;
    bool allowEditLoanProduct = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        appPath = Utils.GetApplicationPath(Request);
        Utils.GetMaster(this).PerformPreloadActions(mCurrentModule, mPageName);

        try
        {
            allowViewLoanProduct = Utils.PermissionAllowed(mCurrentModule, Credits.Domains.ManageLoanProducts.Name, Constants.Constants.Classifiers.Permissions_View);
            allowEditLoanProduct = Utils.PermissionAllowed(mCurrentModule, Credits.Domains.ManageLoanProducts.Name, Constants.Constants.Classifiers.Permissions_Edit);

            addNewProductButton.Visible = allowEditLoanProduct;

            if (allowViewLoanProduct)
            { 
                if (!IsPostBack)
                {
                    ShowPanel(productsListPanel.ID);
                }               
            }
            else
            {
                Response.Redirect(Utils.GetApplicationPath(Request) + "/AccessDenied.aspx");
            }           
        }
        catch (Exception ex)
        { Utils.InfoText(this, "Eroare in System!", ex.Message.ToString()); } 
    }

    private void ShowPanel(string panelName)
    {
        #region Hide panels
        productsListPanel.Visible = false;
        detailsPanel.Visible = false;
        emptyPanel.Visible = false;
        #endregion Hide panels

        try
        {
            #region Get Panel Name

            switch (panelName)
            {
                case "productsListPanel":
                    productsListPanel.Visible = true;
                    FillCreditProductsGridView();
                    break;

                case "detailsPanel":
                    detailsPanel.Visible = true;

                    DataTable list = Utils.ModuleMain().GetClassifierByTypeID((int)Constants.Constants.ClassifierTypes.typeOfCalculation);
                    Utils.FillSelector(loanProdCalculatePercentFromDLL, list, "Name", "Code");

                    DataTable calcPenFrom = Utils.ModuleMain().GetClassifierByTypeID((int)Constants.Constants.ClassifierTypes.CalculatePenaltyFrom);
                    Utils.FillSelector(calculatePenaltyFromDDL, calcPenFrom, "Name", "Code");

                    DataTable minimPercentPeriod = Utils.ModuleMain().GetClassifierByTypeID((int)Constants.Constants.ClassifierTypes.MinimProcentPeriod);
                    Utils.FillSelector(loanProductMinimPercentPeriodDLL, minimPercentPeriod, "Name", "Code");

                    FillAccountingDDLs();
                    break;

                default:
                    emptyPanel.Visible = true;
                    break;
            }

            #endregion Get Panel Name
        }
        catch (Exception ex)
        {
            Utils.InfoText(this, "Atentie! Eroare in sistem!", ex.Message);
        }
    }

    protected void FillAccountingDDLs()
    {
        DataTable planconturi = Utils.ModuleAccounting().GetPlanContList();
        if (planconturi != null) planconturi.Rows.InsertAt(planconturi.NewRow(), 0);
        Utils.FillSelector(cash_fundSourceAccountDDL, planconturi, "Den", "PlanContID");
        Utils.FillSelector(cash_loanPortfolioAccountIdDDL, planconturi, "Den", "PlanContID");
        Utils.FillSelector(cash_transferInSuspenceDDL, planconturi, "Den", "PlanContID");
        Utils.FillSelector(cash_interestOnLoanAccountIdDDL, planconturi, "Den", "PlanContID");
        Utils.FillSelector(cash_incomeFromFeeAccountIdDDL, planconturi, "Den", "PlanContID");
        Utils.FillSelector(cash_incomeFromPenaltyAccountIdDDL, planconturi, "Den", "PlanContID");
        Utils.FillSelector(cash_incomeFromRecoveryAccountIdDDL, planconturi, "Den", "PlanContID");
        Utils.FillSelector(cash_writeOffAccountIdDDL, planconturi, "Den", "PlanContID");
        Utils.FillSelector(cash_overpaymentLiabilityAccountIdDDL, planconturi, "Den", "PlanContID");
    }

    protected void FillCreditProductsGridView()
    {
        DataTable clientsDT = Utils.ModuleCredits().GetLoanProductsDisplayList();
        loanProductsGridView.DataSource = clientsDT;
        loanProductsGridView.DataBind();
    }

    protected void loanProductsGridView_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
    {
        loanProductsGridView.PageIndex = e.NewPageIndex;
        ShowPanel(productsListPanel.ID);  
    }

    protected void loanProductsGridView_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
            e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";

            for (int i = 0; i < e.Row.Cells.Count - 1; i++)
            {
                e.Row.Cells[i].Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.loanProductsGridView, "Select$" + e.Row.RowIndex);
            }
        }
    }

    protected void loanProductsGridView_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
    {
        if (allowEditLoanProduct)
        {
            int index = e.RowIndex;
            int productID = 0;
            int.TryParse(loanProductsGridView.Rows[index].Cells[0].Text, out productID);

            string name = loanProductsGridView.Rows[index].Cells[1].Text;

            if (productID != 0 && Utils.ModuleCredits().DeleteLoanProduct(productID))
            {
                ShowPanel(productsListPanel.ID);
            }
            else
            {
                Utils.InfoText(this, "Atentie", " Produsul { " + name + " } - nu a fost sters. Verificati conectiunea cu internet ");
            }
        }
        else
        { Response.Redirect(Utils.GetApplicationPath(Request) + "/AccessDenied.aspx"); }
    }

    protected void loanProductsGridView_SelectedIndexChanged(object sender, EventArgs e)
    {
        newProductSelectedHiddenField.Value = string.Empty;
        GridViewRow row = loanProductsGridView.SelectedRow;

        string clientID = row.Cells[0].Text;
        detailsPanel.Visible = true;
        selectedProductID_HiddenField.Value = clientID;

        int IntLoanID = 0;
        int.TryParse(clientID, out IntLoanID);
        DataTable loanPr = Utils.ModuleCredits().GetLoanProductByID(IntLoanID);

        if (loanPr != null && loanPr.Rows.Count == 1)
        {
            ShowPanel(detailsPanel.ID);
            FillDetailsTabPanel(loanPr);
        }
    }

    private void FillDetailsTabPanel(DataTable loanPr)
    {
        ClearDetailsProductTabControls();
       
        loanProdNameTextBox.Text = loanPr.Rows[0]["productName"].ToString();
        loanProdCodeTextBox.Text = loanPr.Rows[0]["productCode"].ToString();

        gracePeriodMinTextBox.Text = loanPr.Rows[0]["preferentialPeriodMin"].ToString();
        gracePeriodMaxTextBox.Text = loanPr.Rows[0]["preferentialPeriodMax"].ToString();
        gracePeriodValTextBox.Text = loanPr.Rows[0]["preferentialPeriodValue"].ToString();

        creditAmountMinTextBox.Text = loanPr.Rows[0]["creditAmountMin"].ToString();
        creditAmountMaxTextBox.Text = loanPr.Rows[0]["creditAmountMax"].ToString();
        creditAmountValTextBox.Text = loanPr.Rows[0]["creditAmountValue"].ToString();

        percentMinTextBox.Text = loanPr.Rows[0]["percentMin"].ToString();
        percentMaxTextBox.Text = loanPr.Rows[0]["percentMax"].ToString();
        percentValTextBox.Text = loanPr.Rows[0]["percentValue"].ToString();

        paymantsCountMinTextBox.Text = loanPr.Rows[0]["paymentsCountMin"].ToString();
        paymantsCountMaxTextBox.Text = loanPr.Rows[0]["paymnetsCountMax"].ToString();
        paymantsCountValTextBox.Text = loanPr.Rows[0]["paymnetsCountValue"].ToString();

        penaltyFromPastDueAmountMin_TextBox.Text = loanPr.Rows[0]["penaltyPercentMin"].ToString();
        penaltyFromPastDueAmountMax_TextBox.Text = loanPr.Rows[0]["penaltyPercentMax"].ToString();
        penaltyFromPastDueAmountValue_TextBox.Text = loanPr.Rows[0]["penaltyPercentValue"].ToString();

        try
        {
            loanProdCalculatePercentFromDLL.SelectedValue = loanPr.Rows[0]["calculatePercentFrom"].ToString();
            calculatePenaltyFromDDL.SelectedValue = loanPr.Rows[0]["calculatePenaltyFrom"].ToString();
            loanProductMinimPercentPeriodDLL.SelectedValue = loanPr.Rows[0]["minimPercentPeriod"].ToString();
        }
        catch(Exception ex)
        {
            Utils.InfoText(this, "Eroare in sistem", ex.Message);
        }
    }

 
    protected void addNewProductButton_Click(object sender, EventArgs e)
    {
        newProductSelectedHiddenField.Value = "New";
        ClearDetailsProductTabControls();
        ShowPanel(detailsPanel.ID);
    }

    protected void detailsLoanProductSaveButton_Click(object sender, EventArgs e)
    {
        if (allowEditLoanProduct)
        {
            string productID = selectedProductID_HiddenField.Value;
            string productName = loanProdNameTextBox.Text.Trim();
            string productCode = loanProdCodeTextBox.Text.Trim();

            int calculatePercentFrom = 0;
            int.TryParse(loanProdCalculatePercentFromDLL.SelectedValue, out calculatePercentFrom);

            int gracePeriodMin = 0;
            int.TryParse(gracePeriodMinTextBox.Text, out gracePeriodMin);

            int gracePeriodMax = 0;
            int.TryParse(gracePeriodMaxTextBox.Text, out gracePeriodMax);

            int gracePeriodVal = 0;
            int.TryParse(gracePeriodValTextBox.Text, out gracePeriodVal);

            int creditAmountMin = 0;
            int.TryParse(creditAmountMinTextBox.Text, out creditAmountMin);

            int creditAmountMax = 0;
            int.TryParse(creditAmountMaxTextBox.Text, out creditAmountMax);

            int creditAmountVal = 0;
            int.TryParse(creditAmountValTextBox.Text, out creditAmountVal);

            decimal percentMin = 0;
            decimal.TryParse(percentMinTextBox.Text, out percentMin);

            decimal percentMax = 0;
            decimal.TryParse(percentMaxTextBox.Text, out percentMax);

            decimal percentVal = 0;
            decimal.TryParse(percentValTextBox.Text, out percentVal);

            int paymentsCountMin = 0;
            int.TryParse(paymantsCountMinTextBox.Text, out paymentsCountMin);

            int paymentsCountMax = 0;
            int.TryParse(paymantsCountMaxTextBox.Text, out paymentsCountMax);

            int paymentsCountVal = 0;
            int.TryParse(paymantsCountValTextBox.Text, out paymentsCountVal);

            decimal penaltyPernectMin = 0;
            decimal.TryParse(penaltyFromPastDueAmountMin_TextBox.Text, out penaltyPernectMin);

            decimal penaltyPernectMax = 0;
            decimal.TryParse(penaltyFromPastDueAmountMax_TextBox.Text, out penaltyPernectMax);

            decimal penaltyPernectValue = 0;
            decimal.TryParse(penaltyFromPastDueAmountValue_TextBox.Text, out penaltyPernectValue);

            int calculatePenaltyFrom = 0;
            int.TryParse(calculatePenaltyFromDDL.SelectedValue, out calculatePenaltyFrom);

            int minimPercentPeriod = 0;
            int.TryParse(loanProductMinimPercentPeriodDLL.SelectedValue, out minimPercentPeriod);

            int currencyID = 2; ///  Default MDL

            bool resultoperation = false;

            if (newProductSelectedHiddenField.Value.Equals("New"))
            {
                resultoperation = Utils.ModuleCredits().AddNewLoanProduct(productName
                                                                                            , productCode
                                                                                            , gracePeriodMin
                                                                                            , gracePeriodMax
                                                                                            , gracePeriodVal
                                                                                            , creditAmountMin
                                                                                            , creditAmountMax
                                                                                            , creditAmountVal
                                                                                            , percentMin
                                                                                            , percentMax
                                                                                            , percentVal
                                                                                            , paymentsCountMin
                                                                                            , paymentsCountMax
                                                                                            , paymentsCountVal
                                                                                            , calculatePercentFrom
                                                                                            , penaltyPernectMin
                                                                                            , penaltyPernectMax
                                                                                            , penaltyPernectValue
                                                                                            , calculatePenaltyFrom
                                                                                            , currencyID
                                                                                            , minimPercentPeriod);
            }
            else
            {
                resultoperation = Utils.ModuleCredits().UpdateLoanProduct(productID
                                                                                            , productName
                                                                                            , productCode
                                                                                            , gracePeriodMin
                                                                                            , gracePeriodMax
                                                                                            , gracePeriodVal
                                                                                            , creditAmountMin
                                                                                            , creditAmountMax
                                                                                            , creditAmountVal
                                                                                            , percentMin
                                                                                            , percentMax
                                                                                            , percentVal
                                                                                            , paymentsCountMin
                                                                                            , paymentsCountMax
                                                                                            , paymentsCountVal
                                                                                            , calculatePercentFrom
                                                                                            , penaltyPernectMin
                                                                                            , penaltyPernectMax
                                                                                            , penaltyPernectValue
                                                                                            , calculatePenaltyFrom
                                                                                            , currencyID
                                                                                            , minimPercentPeriod);
            }

            if (resultoperation)
            {
                ShowPanel(productsListPanel.ID);
                Utils.InfoText(this, "Felicitari", "Detalii despre PRODUS au fost salvate! ");
                newProductSelectedHiddenField.Value = string.Empty;
            }
            else
            {
                Utils.InfoText(this, "Atentie", " Datele nu a fost salvate. Verificati conectiunea cu internet ");
            }
        }
        else
        { Response.Redirect(Utils.GetApplicationPath(Request) + "/AccessDenied.aspx"); }
    }

    protected void detailsLoanProductCancelButton_Click(object sender, EventArgs e)
    {
        newProductSelectedHiddenField.Value = string.Empty;
        ShowPanel(productsListPanel.ID);
        ClearDetailsProductTabControls();
    }

    protected void ClearDetailsProductTabControls()
    {
        loanProdNameTextBox.Text = string.Empty;
        loanProdCodeTextBox.Text = string.Empty;

        gracePeriodMinTextBox.Text = string.Empty;
        gracePeriodMaxTextBox.Text = string.Empty;
        gracePeriodValTextBox.Text = string.Empty;

        creditAmountMinTextBox.Text = string.Empty;
        creditAmountMaxTextBox.Text = string.Empty;
        creditAmountValTextBox.Text = string.Empty;

        percentMinTextBox.Text = string.Empty;
        percentMaxTextBox.Text = string.Empty;
        percentValTextBox.Text = string.Empty;

        paymantsCountMinTextBox.Text = string.Empty;
        paymantsCountMaxTextBox.Text = string.Empty;
        paymantsCountValTextBox.Text = string.Empty;

        penaltyFromPastDueAmountMin_TextBox.Text = string.Empty; ;
        penaltyFromPastDueAmountMax_TextBox.Text = string.Empty;
        penaltyFromPastDueAmountValue_TextBox.Text = string.Empty;

        loanProdCalculatePercentFromDLL.SelectedIndex = -1;
        calculatePenaltyFromDDL.SelectedIndex = -1;
        loanProductMinimPercentPeriodDLL.SelectedIndex = -1;
    }

    protected void ClearCashDDLs()
    {
        try { cash_fundSourceAccountDDL.SelectedIndex = 0; } catch { }
        try { cash_loanPortfolioAccountIdDDL.SelectedIndex = 0; } catch { }
        try { cash_transferInSuspenceDDL.SelectedIndex = 0; } catch { }
        try { cash_interestOnLoanAccountIdDDL.SelectedIndex = 0; } catch { }
        try { cash_incomeFromFeeAccountIdDDL.SelectedIndex = 0; } catch { }
        try { cash_incomeFromPenaltyAccountIdDDL.SelectedIndex = 0; } catch { }
        try { cash_incomeFromRecoveryAccountIdDDL.SelectedIndex = 0; } catch { }
        try { cash_writeOffAccountIdDDL.SelectedIndex = 0; } catch { }
        try { cash_overpaymentLiabilityAccountIdDDL.SelectedIndex = 0; } catch { }
    }

    protected void ClearAccurlDDLs()
    {
        try { accural_fundSourceAccountDDL.SelectedIndex = 0; } catch { }
        try { accural_loanPortfolioAccountIdDDL.SelectedIndex = 0; } catch { }
        try { accural_transferInSuspenceDDL.SelectedIndex = 0; } catch { }
        try { accural_interestOnLoanAccountIdDDL.SelectedIndex = 0; } catch { }
        try { accural_incomeFromFeeAccountIdDDL.SelectedIndex = 0; } catch { }
        try { accural_incomeFromPenaltyAccountIdDDL.SelectedIndex = 0; } catch { }
        try { accural_incomeFromRecoveryAccountIdDDL.SelectedIndex = 0; } catch { }
        try { accural_writeOffAccountIdDDL.SelectedIndex = 0; } catch { }
        try { accural_overpaymentLiabilityAccountIdDDL.SelectedIndex = 0; } catch { }
    }


    protected void accountingNoneRadioButton_CheckedChanged(object sender, EventArgs e)
    {
        ClearCashDDLs();
        ClearAccurlDDLs();

        cashPanel.Visible = false;
        accuralPanel.Visible = false;

        //accountingNoneRadioButton.Checked = 
        //accountingCashRadioButton.Checked = !accountingNoneRadioButton.Checked;
        //accountingAccuralRadioButton.Checked = 
        //accountingAccuralUpfrontRadioButton.Checked = 

        accountingCashRadioButton.Checked = !accountingNoneRadioButton.Checked;
        accountingAccuralRadioButton.Checked = !accountingNoneRadioButton.Checked;
        accountingAccuralUpfrontRadioButton.Checked = !accountingNoneRadioButton.Checked;
    }

    protected void accountingCashRadioButton_CheckedChanged(object sender, EventArgs e)
    {
        ClearAccurlDDLs();

        cashPanel.Visible = true;
        accuralPanel.Visible = false;

        accountingNoneRadioButton.Checked = !accountingCashRadioButton.Checked;
        accountingAccuralRadioButton.Checked = !accountingCashRadioButton.Checked;
        accountingAccuralUpfrontRadioButton.Checked = !accountingCashRadioButton.Checked;
    }

    protected void accountingAccuralRadioButton_CheckedChanged(object sender, EventArgs e)
    {
        ClearCashDDLs();

        cashPanel.Visible = false;
        accuralPanel.Visible = true;

        accountingNoneRadioButton.Checked = !accountingAccuralRadioButton.Checked;
        accountingCashRadioButton.Checked = !accountingAccuralRadioButton.Checked;
        accountingAccuralUpfrontRadioButton.Checked = !accountingAccuralRadioButton.Checked;
    }

    protected void accountingAccuralUpfrontRadioButton_CheckedChanged(object sender, EventArgs e)
    {
        accountingNoneRadioButton.Checked = !accountingAccuralUpfrontRadioButton.Checked;
        accountingCashRadioButton.Checked = !accountingAccuralUpfrontRadioButton.Checked;
        accountingAccuralRadioButton.Checked = !accountingAccuralUpfrontRadioButton.Checked;
    }
}